import asyncio
import time


async def my_task(m):
    await asyncio.sleep(2)
    return f"Task completed :{m}"


async def main():
    try:
        coroutine20 = my_task(20)
        coroutine40 = my_task(40)
        coroutine60 = my_task(60)
        coroutine80 = my_task(80)
        tasks = [coroutine20, coroutine40, coroutine60, coroutine80]

        # 使用 asyncio.gather 来等待所有任务完成，并获取它们的返回值
        result = await asyncio.gather(*tasks)
        for task in result:
            print(task)
    except asyncio.CancelledError:
        # 取消所有任务
        for task in asyncio.all_tasks():
            task.cancel()
        await asyncio.gather(*asyncio.all_tasks(), return_exceptions=True)
        print("Caught CancelledError, all tasks were cancelled.")
    except KeyboardInterrupt:
        print("Caught KeyboardInterrupt, cancelling all tasks.")
        for task in asyncio.all_tasks():
            task.cancel()
        await asyncio.gather(*asyncio.all_tasks(), return_exceptions=True)


if __name__ == "__main__":
    start = time.time()
    try:
        # 直接运行 main 协程，而不是使用 asyncio.run()
        asyncio.run(main())
    except Exception as e:
        print(f"An exception occurred: {e}")

    # 打印总运行时间
    print(f"Time is :{time.time() - start}")
